<?php
/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not
 *  exist, see <http://www.gnu.org/licenses/>.
 *
 * $LastChangedDate: 2008-07-15 00:09:39 +0200 (Tue, 15 Jul 2008) $
 * $Rev: 1295 $
 * $Author: gavinspearhead $
 * $Id: newsgroups.php 1295 2008-07-14 22:09:39Z gavinspearhead $
 */
define('ORIGINAL_PAGE', $_SERVER['PHP_SELF']);

$pathstat = realpath(dirname(__FILE__));

require_once "$pathstat/../functions/html_includes.php" ;

$isadmin = is_admin($db, $userID);
$title = $LN['stats_title'];

$types = array(STAT_ACTION_DOWNLOAD, STAT_ACTION_PREVIEW, STAT_ACTION_IMPORTNZB, STAT_ACTION_GETNZB, STAT_ACTION_WEBVIEW, STAT_ACTION_POST);

$langtypes = array();
$langtypes[STAT_ACTION_DOWNLOAD] = $LN['stats_dl'];
$langtypes[STAT_ACTION_PREVIEW]  = $LN['stats_pv'];
$langtypes[STAT_ACTION_IMPORTNZB]= $LN['stats_im'];
$langtypes[STAT_ACTION_GETNZB]   = $LN['stats_gt'];
$langtypes[STAT_ACTION_WEBVIEW]  = $LN['stats_wv'];
$langtypes[STAT_ACTION_POST]     = $LN['stats_ps'];

$nametypes = array();
$nametypes[STAT_ACTION_DOWNLOAD] = 'stats_dl';
$nametypes[STAT_ACTION_PREVIEW]  = 'stats_pv';
$nametypes[STAT_ACTION_IMPORTNZB]= 'stats_im';
$nametypes[STAT_ACTION_GETNZB]   = 'stats_gt';
$nametypes[STAT_ACTION_WEBVIEW]  = 'stats_wv';
$nametypes[STAT_ACTION_POST]     = 'stats_ps';

$monthnames[1] = $LN['month_jan'];
$monthnames[2] = $LN['month_feb'];
$monthnames[3] = $LN['month_mar'];
$monthnames[4] = $LN['month_apr'];
$monthnames[5] = $LN['month_may'];
$monthnames[6] = $LN['month_jun'];
$monthnames[7] = $LN['month_jul'];
$monthnames[8] = $LN['month_aug'];
$monthnames[9] = $LN['month_sep'];
$monthnames[10] = $LN['month_oct'];
$monthnames[11] = $LN['month_nov'];
$monthnames[12] = $LN['month_dec'];

/* Determine valid years and months: */
$now = time();
$month = date('n', $now);
$show_month = $show_year = 0;
if (isset($_REQUEST['year']) && is_numeric($_REQUEST['year'])) {
    $in_year = $_REQUEST['year'];
    $show_month = 1;
} else {
    $in_year = date('Y', $now);
    $show_year = 1;
}

if ($isadmin)
    $quser = "AND \"userid\" = '$userID'";
else 
    $quser = '';

$ystr = ' EXTRACT(year FROM "timestamp") ';
$qry = " $ystr AS \"year\" FROM stats WHERE 1=1 $quser GROUP BY $ystr ORDER BY \"year\" DESC";
$res = $db->select_query($qry);
$years = array();

if (!is_array($res))
    $res = array();

foreach ($res as $row) 
    $years[] = $row['year'];

// Here begins the processing:
$yearstats = new OverallYearStats();
$monthstats = new OverallMonthStats();
foreach ($types as $type) {
    $dl = get_stats_by_year($db, $type, $isadmin, 0, $yearstats);
    $dl = get_stats_by_month($db, $type, $isadmin, $in_year, $monthstats);
}

// Convert definitions to keywords (STAT_ACTION_DOWNLOAD = 1 => 'downloads') to make it accessible in smarty.
convert_stat_definitions($yearstats);
move_total_to_users($yearstats);

convert_stat_definitions($monthstats);
move_total_to_users($monthstats);
enter_month_names($monthstats);

$smarty->assign('years',            $years);
$smarty->assign('show_year',        $show_year);
$smarty->assign('show_month',       $show_month);
$smarty->assign('month_year',       $in_year);
$smarty->assign('yearstats',        $yearstats);
$smarty->assign('monthstats',       $monthstats);

$smarty->assign('title',        'URD - ' .  $title);
$smarty->assign('menu',         generate_menu($LN));


$smarty->display('statistics.tpl');

// ZE END:
die();


/* CLASSES: */

class Stats
{
    public $StatName;
    public $SizeRaw;
    public $SizeNice;
    public $Count;

    function __construct($name = '')
    {
        $this->StatName = $name;
        $this->SizeRaw = 0;
        $this->SizeNice = '';
        $this->Count = 0;
    }
}


class IndividualStats
{
    public $StatType;

    function __construct()
    {
        global $langtypes;
        $this->StatType[STAT_ACTION_DOWNLOAD]   = new Stats($langtypes[STAT_ACTION_DOWNLOAD]);
        $this->StatType[STAT_ACTION_PREVIEW]    = new Stats($langtypes[STAT_ACTION_PREVIEW]);
        $this->StatType[STAT_ACTION_IMPORTNZB]  = new Stats($langtypes[STAT_ACTION_IMPORTNZB]);
        $this->StatType[STAT_ACTION_GETNZB]     = new Stats($langtypes[STAT_ACTION_GETNZB]);
        $this->StatType[STAT_ACTION_WEBVIEW]    = new Stats($langtypes[STAT_ACTION_WEBVIEW]);
        $this->StatType[STAT_ACTION_POST]       = new Stats($langtypes[STAT_ACTION_POST]);
    }
}


class MonthStats
{
    public $MonthName;
    public $Users;
    public $OverallTotal;

    function __construct()
    {
        $this->MonthName = '';
        $this->Users = array();
        $this->OverallTotal = new IndividualStats();
    }

}


class OverallMonthStats
{
    public $Months;
    function __construct() 
    {
        $this->Months = array(); 
    }
}


class YearStats
{
    public $Users;
    public $OverallTotal;

    function __construct()
    {
        $this->Users = array();
        $this->OverallTotal = new IndividualStats();
    }

}


class OverallYearStats
{
    public $Years;
    function __construct() { $this->Years = array(); }
}


/* FUNCTIONS: */

function get_stats_by_year(DatabaseConnection $db, $type, $admin, $fromyear, &$overallyearstats)
{
    global $LN;
    global $langtypes;
    global $userID;

    $ystr = ' EXTRACT(year FROM "timestamp") ';

    $max_cnt = 0;
    $safetype = $type;
    $db->escape ($safetype, TRUE);
    if (!$admin)
        $quser = " AND users.\"ID\" = '$userID' ";
    else
        $quser = '';
    //if ($admin === TRUE) {
    $qry = <<<QRY1
SELECT * FROM ((SELECT sum("value") AS "total", count("action") AS "counter", users."name", $ystr AS "year" FROM stats, users WHERE $ystr > $fromyear 
AND "action" = $safetype AND users."ID" = stats."userid" $quser GROUP BY users."name", $ystr ) 
UNION ( SELECT sum("value") AS "total", count("action") AS "counter", '__total' AS "name", $ystr AS "year" FROM stats WHERE $ystr > $fromyear 
AND "action" = $safetype GROUP BY $ystr)) AS "val" ORDER BY year, "name"
QRY1;
    $res = $db->execute_query($qry);
    if (!is_array($res))
        $res = array();
    // Loop through all users for this type:
    foreach($res as $k => &$row) {
        // Clean up 0/1/2/3/4 stuff:
        for ($x = 0; $x < 5; $x++) 
            if (isset($row["$x"])) 
                unset($row["$x"]);

        if($row['counter'] > $max_cnt)
            $max_cnt = $row['counter'];
        $row['total_nr'] = $row['total'];
        $row['total'] = readable_size($row['total'], 1, $LN['byte_short'] );

        if ($row['name'] ==  '__total') {
            $row['name'] = $LN['total'];
            $row['sum'] = 'true';
        }
    }

    // Parse into structs:
    foreach ($res as $user) {
        $year = $user['year']; 
        $name = $user['name'];
        $issum = isset($user['sum']) ? TRUE : FALSE;
        $total = $user['total'];
        $totalnr = $user['total_nr'];
        $counter = $user['counter'];
        // Check if year exists:
        if (!isset($overallyearstats->Years[$year]))
            $overallyearstats->Years[$year] = new YearStats();

        if ($issum) {
            $overallyearstats->Years[$year]->OverallTotal->StatType[$type]->SizeRaw = $user['total_nr'];
            $overallyearstats->Years[$year]->OverallTotal->StatType[$type]->SizeNice = readable_size($user['total_nr'], 1 , $LN['byte_short']);
            $overallyearstats->Years[$year]->OverallTotal->StatType[$type]->Count = $user['counter'];
            krsort($overallyearstats->Years);
        } else {
            if (!isset($overallyearstats->Years[$year]->Users[$name]))
                $overallyearstats->Years[$year]->Users[$name] = new IndividualStats();

            $overallyearstats->Years[$year]->Users[$name]->StatType[$type]->SizeRaw = $user['total_nr'];
            $overallyearstats->Years[$year]->Users[$name]->StatType[$type]->SizeNice = $user['total'];
            $overallyearstats->Years[$year]->Users[$name]->StatType[$type]->Count = $user['counter'];
            krsort($overallyearstats->Years);
        }
    }
    return $res;
}

// Translate definitions for stats to keywords that can be safely used in smarty without having to worry if the definition values change:
function convert_stat_definitions(&$stats)
{
    if (is_object($stats) && get_class($stats) == 'IndividualStats') {
        foreach ($stats->StatType as $key => $data) {
            $newkey = transform_key($key);
            $stats->StatType[$newkey] = $stats->StatType[$key];
            unset($stats->StatType[$key]);
        }
    }

    if (is_array($stats) || is_object($stats))
        foreach ($stats as $otherobj)
            convert_stat_definitions($otherobj);
}


function transform_key($key)
{
    global $nametypes;
    if (isset($nametypes[$key])) 
        return $nametypes[$key];
    return $key;
}
 

function move_total_to_users(&$stats)
{
    if (is_object($stats) && get_class($stats) == 'OverallYearStats') {
        foreach ($stats->Years as $yearstats) {
            $yearstats->Users['__total'] = $yearstats->OverallTotal;
        }
    }
    if (is_object($stats) && get_class($stats) == 'OverallMonthStats') {
        foreach ($stats->Months as $monthstats) {
            $monthstats->Users['__total'] = $monthstats->OverallTotal;
        }
    }
}


function get_stats_by_month(DatabaseConnection $db, $type, $admin, $year=NULL, &$overallmonthstats)
{
    global $LN, $userID;
    $ystr = ' EXTRACT(year FROM "timestamp") ';
    $mstr = ' EXTRACT(month FROM "timestamp") ';

    if ($year !== NULL) {
        $db->escape($year, TRUE);
        $qyear = "$ystr = $year";
    } else
        $qyear = '1=1';
    $safetype = $type;
    $db->escape ($safetype, TRUE);
    if (!$admin)
        $quser = " AND users.\"ID\" = '$userID' ";
    else
        $quser = '';
    $qry = <<<QRY1
SELECT * FROM ((SELECT sum("value") AS "total", count("action") AS "counter", users."name", $mstr AS "month", $ystr AS "year" FROM stats, users 
WHERE $qyear AND "action" = $safetype AND users."ID" = stats."userid" $quser GROUP BY users."name", $mstr, $ystr ORDER BY users."name")
UNION (SELECT sum("value") AS "total", count("action") AS "counter", '__total' AS "name", $mstr AS "month", $ystr AS "year" FROM stats 
WHERE $qyear AND "action" = $safetype GROUP BY $mstr, $ystr )) AS "val" ORDER BY "name", month, year 
QRY1;
    $res = $db->execute_query ($qry);

    if (!is_array($res))
        $res = array();
    // Loop through all users for this type:
    foreach($res as $k => &$row)    {
        // Clean up 0/1/2/3/4 stuff:
        for ($x = 0; $x < 5; $x++) 
            if (isset($row["$x"])) 
                unset($row["$x"]);

        $row['total_nr'] = $row['total'];
        $row['total'] = readable_size($row['total'], 1 , $LN['byte_short']);

        if ($row['name'] ==  '__total') {
            $row['name'] = $LN['total'];
            $row['sum'] = 'true';
        }

    }

    // Parse into structs:
    foreach ($res as $user) {
        $year = $user['year'];
        $month = $user['month'];
        $name = $user['name'];
        $issum = isset($user['sum']) ? TRUE : FALSE;
        $total = $user['total'];
        $totalnr = $user['total_nr'];
        $counter = $user['counter'];

        // Check if year exists:
        if (!isset($overallmonthstats->Months[$month]))
            $overallmonthstats->Months[$month] = new MonthStats();

        if ($issum) {
            $overallmonthstats->Months[$month]->OverallTotal->StatType[$type]->SizeRaw = $user['total_nr'];
            $overallmonthstats->Months[$month]->OverallTotal->StatType[$type]->SizeNice = readable_size($user['total_nr'], 1 , $LN['byte_short']);
            $overallmonthstats->Months[$month]->OverallTotal->StatType[$type]->Count = $user['counter'];
            ksort(  $overallmonthstats->Months);
        } else {
            if (!isset($overallmonthstats->Months[$month]->Users[$name]))
                $overallmonthstats->Months[$month]->Users[$name] = new IndividualStats();

            $overallmonthstats->Months[$month]->Users[$name]->StatType[$type]->SizeRaw = $user['total_nr'];
            $overallmonthstats->Months[$month]->Users[$name]->StatType[$type]->SizeNice = $user['total'];
            $overallmonthstats->Months[$month]->Users[$name]->StatType[$type]->Count = $user['counter'];
            ksort(  $overallmonthstats->Months);
        }
    }
}


function enter_month_names(&$overallmonthstats)
{
    global $monthnames;
    foreach ($overallmonthstats->Months as $monthnumber => $monthobj)
        $monthobj->MonthName = $monthnames[$monthnumber];
}


?>
